package com.example.myapplication.part11;

import android.os.Bundle;
import android.os.Handler;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.R;

import java.util.ArrayList;
import java.util.List;

public class Part11Activity extends AppCompatActivity {
    private ListView chatListView;
    private EditText messageInput;
    private Button sendButton;
    private List<Message> messages = new ArrayList<>();
    private ChatAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_part11);

        chatListView = findViewById(R.id.chatListView);
        messageInput = findViewById(R.id.messageInput);
        sendButton = findViewById(R.id.sendButton);

        adapter = new ChatAdapter(this, messages);
        chatListView.setAdapter(adapter);

        setupListeners();
    }

    private void setupListeners() {
        sendButton.setOnClickListener(v -> sendMessage());

        messageInput.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                sendMessage();
                return true;
            }
            return false;
        });
    }

    private void sendMessage() {
        String text = messageInput.getText().toString().trim();
        if (!text.isEmpty()) {
            Message userMessage = new Message(text, true);
            messages.add(userMessage);
            adapter.notifyDataSetChanged();

            simulateBotResponse(userMessage.getText());

            messageInput.setText("");
            scrollToBottom();
        }
    }

    private void simulateBotResponse(String input) {
        new Handler().postDelayed(() -> {
            String botText = generateBotResponse(input);
            Message botMessage = new Message(botText, false);
            messages.add(botMessage);
            adapter.notifyDataSetChanged();
            scrollToBottom();
        }, 1000); // 1秒延迟模拟响应时间
    }

    private String generateBotResponse(String input) {
        // 简单的回复逻辑
        if (input.contains("你好")) {
            return "你好！我是聊天机器人";
        } else if (input.contains("天气")) {
            return "今天天气晴朗，温度25°C";
        } else if (input.contains("明星")) {
            return "易烊千玺";
         } else {
            return "我不太明白您的意思，请换个说法";
        }
    }

    private void scrollToBottom() {
        chatListView.post(() -> {
            int position = messages.size() - 1;
            if (position >= 0) {
                chatListView.smoothScrollToPosition(position);
            }
        });
    }
}